package com.yc.sole.job;

import com.yc.sole.erp.dto.ProductDto;
import com.yc.sole.erp.dto.SaleOrderDto;
import com.yc.sole.erp.repository.ProductRepository;
import com.yc.sole.erp.repository.SaleOrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自动根据最新的订单产品价格更新产品价格
 *
 * @author yizuomin
 * @date 2024/1/27 17:54
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class ProductPriceJob {

    private final ProductRepository productRepository;
    private final SaleOrderRepository saleOrderRepository;

    @Scheduled(cron = "0 0 22 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void run() {
        log.info("产品价格更新-开始执行");
        Map<Long, List<SaleOrderDto>> productOrderMap = saleOrderRepository.selectOrderProductUnitPriceMap();
        Map<Long, ProductDto> productDtoMap = productRepository.selectProductByIds(productOrderMap.keySet()).stream().collect(Collectors.toMap(ProductDto::getId, v -> v));
        // 如果订单存在相同产品-取最高的价格
        for (Long productId : productOrderMap.keySet()) {
            ProductDto productDto = productDtoMap.get(productId);
            if (Objects.isNull(productDto)) {
                continue;
            }
            List<SaleOrderDto> saleOrderDtos = productOrderMap.get(productId);
            Optional<SaleOrderDto> max = saleOrderDtos.stream().max(Comparator.comparing(SaleOrderDto::getUnitPrice));
            if (max.isPresent() && max.get().getUnitPrice().compareTo(productDto.getUnitPrice()) != 0) {
                ProductDto updateDto = new ProductDto();
                updateDto.setId(productDto.getId());
                updateDto.setUnitPrice(max.get().getUnitPrice());
                productRepository.updateProductById(updateDto);
            }
        }
        log.info("产品价格更新-执行结束");
    }
}
